<template>

    <div>
        <el-breadcrumb separator="/" style="color: black;font-weight: 700">
            <el-breadcrumb-item >首页</el-breadcrumb-item>
            <el-breadcrumb-item>登机口管理</el-breadcrumb-item>
        </el-breadcrumb>
        <h1>登机口管理</h1>
        <!--      搜索表单-->
        <el-row :gutter="20">
            <el-col :span="6">
                <el-button type="primary" @click="openAddDialog" style="display: none">添加</el-button>
            </el-col>
            <el-col :span="6">
                <el-form-item label="航班号" >
                    <el-input placeholder="航班号" v-model="searchCriteria.META_ID" clearable />
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="登机口编号" >
                    <el-input placeholder="登机口编号" v-model="searchCriteria.CODE" clearable />
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item>
                    <el-button type="primary" @click="searchOnSubmit">{{ buttonLabel }}</el-button>
                    <el-button @click="searchOnReset">取消</el-button>
                </el-form-item>
            </el-col>
        </el-row>

        <el-table :data="tableData" style="width: 100%">
            <el-table-column
                    :prop="item.prop"
                    :label="item.label"
                    v-for="(item, index) in tableHeader"
                    :key="item.prop"
            >
                <template #default="scope">
                    <div
                            v-show="item.editable || scope.row.editable"
                            class="editable-row"
                    >
                        <template v-if="item.type === 'input'">
                            <!--                            输入框-->
                            <el-input
                                    v-bind="{ readonly: ['ID', 'META_ID'].includes(item.prop) && scope.row.editable }"
                                    size="small"
                                    v-model="scope.row[item.prop]"
                                    :placeholder="`请输入${item.label}`"
                                    @change="handleEdit(scope.$index, scope.row)"
                            />
                        </template>
                        <template v-if="item.type === 'date'">
                            <el-date-picker
                                    v-model="scope.row[item.prop]"
                                    type="datetime"
                                    value-format="YYYY-MM-DD HH:mm:ss"
                                    :placeholder="`请输入${item.label}`"
                                    @change="handleEdit(scope.$index, scope.row)"
                            />
                        </template>

                    </div>

                    <div
                            v-show="!item.editable && !scope.row.editable"
                            class="editable-row"
                    >
                        <span class="editable-row-span">{{ scope.row[item.prop] }}</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="操作" >
                <template #default="scope">
                    <el-button
                            size="small"
                            type="warning"
                            disabled
                    >您没有任何操作权限</el-button
                    >

                </template>
            </el-table-column>
        </el-table>
        <!-- 分页组件示例 -->
      <el-pagination
          background
          :current-page="currentPage"
          style="margin-top: 20px;"
          v-model="currentPage"
          :small="small"
          :disabled="disabled"
          :background="background"
          :page-size="pageSize"
          layout="prev, pager, next, jumper"
          :total=totalElements
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          v-if="showPagination"
      />
        <!-- 新的分页组件，用于搜索结果 -->
      <el-pagination
          v-if="showSearchPagination"
          background
          :total="searchTotalElements"
          :current-page="searchCurrentPage"
          :page-size="searchPageSize"
          @current-change="handleSearchPageChange"
          style="margin-top: 20px;"
          v-model="currentPage"
          :small="small"
          :disabled="disabled"
          :background="background"
          layout="prev, pager, next, jumper"
          @size-change="handleSizeChange"
      />
        <!-- 添加飞机信息模态框 -->
        <el-dialog v-model="dialogVisible" title="添加登机口信息" width="50%" @close="resetAddForm">
            <el-form ref="addFormRef" :model="newFlight" label-width="80px">
                <el-form-item label="航班号">
                    <el-input v-model="newFlight.META_ID" placeholder="请输入航班号[只能是数字，且是6位]"/>
                </el-form-item>
                <el-form-item label="机口序号">
                    <el-input v-model="newFlight.gtno" />
                </el-form-item>
                <el-form-item label="机口编号">
                    <el-input v-model="newFlight.code" />
                </el-form-item>
                <el-form-item label="所属楼号">
                    <el-input v-model="newFlight.btsc" />
                </el-form-item>
                <el-form-item label="开始时间">
                    <el-date-picker
                            v-model="newFlight.estr"
                            type="datetime"
                            value-format="YYYY-MM-DD hh:mm:ss"
                            placeholder="选择日期"
                    />
                </el-form-item>
                <el-form-item label="结束时间">
                    <el-date-picker
                            v-model="newFlight.eend"
                            type="datetime"
                            value-format="YYYY-MM-DD hh:mm:ss"
                            placeholder="选择日期"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onAddHandler">确定</el-button>
      </span>
            </template>
        </el-dialog>
    </div>
</template>


<script setup>
    import { ref, reactive, onMounted,onUpdated,computed,nextTick } from 'vue';
    import {ElMessage, ElMessageBox} from 'element-plus'
    import axios from 'axios'; // 确保已导入axios
    const small = ref(false)
    const background = ref(true)
    const disabled = ref(false)

    const handleSizeChange = (val) => {
      console.log(`${val} items per page`)
    }
    const item = reactive({
        ID: "",
        META_ID: "",
        GTNO: "",
        CODE:"",
        BTSC:"",
        ESTR:"",
        EEND:"",
        VALID: "",
        displayStatus:"",
    });

    const header = {
        prop: "key",
        label: "自定义",
        editable: false,
        type: "input",
    };
    //表头
    const tableHeader = ref([
        // {
        //     prop: "ID",
        //     label: "ID",
        //     editable: false,
        //     type: "input",
        // },
        {
            prop: "META_ID",
            label: "航班号",
            editable: false,
            type: "input"
        },
        {
            prop: "GTNO",
            label: "登机口序号",
            editable: false,
            type: "input"
        },
        {
            prop: "CODE",
            label: "登机口编号",
            editable: false,
            type: "input"
        },
        {
            prop: "BTSC",
            label: "登机口所属楼号",
            editable: false,
            type: "input"
        },
        {
            prop: "ESTR",
            label: "登机口开始时间",
            editable: false,
            type: "date"
        },
        {
            prop: "EEND",
            label: "登机口结束时间",
            editable: false,
            type: "date"
        },
        {
            prop: "displayStatus",
            label: "状态",
            editable: false,
            type: "select", // 将类型更改为'select'
            options: [
                { label: "启用", value: 1 },
                { label: "禁用", value: 0 },
            ],
        },
    ]);
    //表单内数据，从数据库获取
    const tableData = ref([]);

    // 分页相关状态
    const currentPage = ref(1); // 当前页码，默认为第一页
    const pageSize = ref(7); // 每页显示数量，默认为7条
    const totalElements = ref(0);

    // 添加分页导航的处理函数，比如上一页、下一页、跳转到特定页
    function handleSearchPageChange(page) {
        searchCurrentPage.value = page;
        searchOnSubmit(page);
    }

    // 更新fetchFlightData函数以支持分页查询
    async function fetchFlightData(current = currentPage.value, size = pageSize.value) {
        try {
            const response = await axios.get('/board/page', {
                params: {
                    currentPage: current,
                    pageSize: size
                }
            });

            if (!response.data.errorCode || response.data.errorCode === "200") {
                // 更新tableData时，考虑分页数据结构
                tableData.value = response.data.data.map(flight => ({
                    ID: flight.id,
                    META_ID: flight.META_ID,
                    GTNO: flight.gtno,
                    CODE: flight.code,
                    BTSC: flight.btsc,
                    ESTR: flight.estr,
                    EEND: flight.eend,
                    VALID: flight.valid,
                    // 添加新属性用于展示，根据VALID值决定
                    displayStatus: flight.valid === 1 ? '启用' : '禁用',
                }));
                totalElements.value = response.data.total;
            } else {
                ElMessage.error(response.data.msg || '获取数据失败');
                console.error('Failed to fetch data. ErrorCode:', response.data.errorCode, ', Message:', response.data.msg);
            }
        } catch (error) {
            ElMessage.error('获取数据过程中发生错误');
            console.error('Error fetching data:', error);
        }
    }

    // 初始化时加载第一页数据
    onMounted(() => {
        fetchFlightData();
        showPagination.value=true;
    });
    onUpdated(() => {
    });


    // 添加分页导航的处理函数，比如上一页、下一页、跳转到特定页
    function handleCurrentChange(page) {
        currentPage.value = page;
        fetchFlightData(page);
    }



    //模糊查询
    const searchCriteria = reactive({
        META_ID: "",
        CODE: "",
    });

    const showPagination = ref(true);

    const buttonLabel = computed(() => {
        // showSearchPagination.value=  false;
        showPagination.value =
            searchCriteria.META_ID.trim() !== ''
            || searchCriteria.CODE.trim() !== '';
        return searchCriteria.META_ID.trim() === ''
        && searchCriteria.CODE.trim() === ''
            ? '查询所有'
            : '条件查询';
    });

    const searchCurrentPage = ref(1);
    const searchPageSize = ref(7);
    const searchTotalElements = ref(0);
    const showSearchPagination = ref(false);

    async function searchOnSubmit() {
        // if (!searchCriteria.META_ID) {
        //     ElMessage.warning('请输入航班号');
        //     return;
        // }
        // //判断是否输入的是6位数字
        // if (!/^\d{6}$/.test(searchCriteria.META_ID)) {
        //     ElMessage.error('请输入6位数字航班号');
        //     return;
        // }
        try {
            const response = await axios.get('/board/findBy', {
                params: {
                    ...searchCriteria,
                    currentPage: searchCurrentPage.value,
                    pageSize: searchPageSize.value,
                }
            });

            if (!response.data.errorCode || response.data.errorCode === "200") {
                tableData.value = response.data.data.map(flight => ({
                    ID: flight.id,
                    META_ID: flight.META_ID,
                    GTNO: flight.gtno,
                    CODE: flight.code,
                    BTSC: flight.btsc,
                    ESTR: flight.estr,
                    EEND: flight.eend,
                    VALID: flight.valid,
                    // 添加新属性用于展示，根据VALID值决定
                    displayStatus: flight.valid === 1 ? '启用' : '禁用',
                }));
                searchTotalElements.value = response.data.total;
                if (response.data.total > 10) {
                    showSearchPagination.value = true; // 显示搜索结果的分页
                }
                showPagination.value = false; // 隐藏原来的分页
            } else if (response.data.errorCode === "404") {
                ElMessage.error('未找到航班号，请检查您的航班号是否有误');
            }
        } catch (error) {
            ElMessage.error('查询过程中发生错误');
            console.error('查询错误:', error);
        }
    }
    //取消
    //取消
    const searchOnReset = async () => {
        searchCriteria.META_ID = "";
        searchCriteria.CODE = "";
        await fetchFlightData();
        showPagination.value = true;
        showSearchPagination.value = false;
    };


    //切换表格行进入编辑模式
    function handleEdit(row) {
        row.editable = true;
    }

    //删除
    async function deleteFlightData(ID) {
        // 使用ElMessageBox显示确认对话框
        const confirmResult = await ElMessageBox.confirm(
            '确定要删除这条登机口信息吗？',
            '删除确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );
        // 如果用户点击了确认按钮（confirm）
        if (confirmResult === 'confirm') {
            try {
                const response = await axios.delete(`/board/${ID}`);

                if (!response.data.errorCode || response.data.errorCode === "200") {
                    await fetchFlightData();
                    ElMessage.success('删除成功');
                } else {ElMessage.error('删除失败，请重试');}
            } catch (error) {
                console.error('Error deleting data:', error);
                ElMessage.error('删除失败');
            }
        }
        // 如果用户点击取消，则什么都不做，对话框自动关闭
    }

    //

    // 添加飞机信息的对话框状态
    const dialogVisible = ref(false);

    // 新飞机信息对象
    const newFlight = reactive({
        META_ID: "",
        gtno: "",
        code: "",
        btsc: "",
        estr: "",
        eend: "",
    });
    // 添加表单的引用
    const addFormRef = ref(null);
    // 打开添加飞机信息的模态框
    const openAddDialog = () => {
        dialogVisible.value = true;
    };
    // 重置添加表单
    const resetAddForm = () => {
        newFlight.META_ID = "";
        newFlight.gtno = "";
        newFlight.code = "";
        newFlight.btsc = "";
        newFlight.estr = "";
        newFlight.eend = "";
    };
    // 添加飞机信息的处理函数
    async function onAddHandler() {
        try {
            // 验证表单是否非空
            if (
                !newFlight.META_ID ||
                !newFlight.gtno ||
                !newFlight.code ||
                !newFlight.btsc ||
                !newFlight.estr ||
                !newFlight.eend
            ) {
                ElMessage.warning('请填写完整的信息');
                return;
            }
            //验证META_ID是否是数字，如果不是，则提示错误
            if (!/^\d{6}$/.test(newFlight.META_ID)) {
                ElMessage.warning('航班号格式不正确，请输入正确的格式[六位数字]');
                return;
            }
            // 发送添加请求到后端
            const response = await axios.post('/board/insert', newFlight);

            if (!response.data.errorCode || response.data.errorCode === "200") {
                ElMessage.success('添加成功');
                dialogVisible.value = false; // 关闭模态框
                await fetchFlightData(); // 刷新表格数据
            } else {
                ElMessage.error(response.data.msg || '添加失败，请重试');
            }
        } catch (error) {
            console.error('Error adding data:', error);
            ElMessage.error('添加过程中发生错误');
        }
    }



    // 修改
    async function saveEditedRow(row) {
        if (row.displayStatus === '启用'  || row.displayStatus ==='禁用') {
            ElMessage.warning('请再次确认选择一次您的状态');
            return; // 停止执行保存逻辑
        }
        try {
            const updatedFlight = {
                id: row.ID,
                meta_id: row.META_ID,
                gtno: row.GTNO,
                code: row.CODE,
                btsc: row.BTSC,
                estr: row.ESTR,
                eend: row.EEND,
            };
            const response = await axios.put(`/board/update`, updatedFlight);

            if (!response.data.errorCode || response.data.errorCode === "200") {
                ElMessage.success('更新成功');
                row.editable = false;
                await fetchFlightData();
            } else {
                ElMessage.error(response.data.msg || '更新失败，请重试');
            }
        } catch (error) {
            console.error('Error updating data:', error);
            ElMessage.error('更新过程中发生错误');
        }
    }
    //取消修改按钮
    const cancelEdit = (row) => {
        row.editable = false;
        //    恢复原来数据
        Object.assign(row, {
            ID: row.ID,
            META_ID: row.META_ID,
            GTNO: row.GTNO,
            CODE: row.CODE,
            BTSC: row.BTSC,
            ESTR: row.ESTR,
            EEND: row.EEND,
        });
        ElMessage.warning('已取消修改');
        fetchFlightData();
    };

</script>

<style scoped>

.demo-pagination-block + .demo-pagination-block {
  margin-top: 20px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>